/*
 * @FileName: OrganizationService.java
 * 
 * @Author
 * 
 * @Description:
 * 
 * @Date 2016年1月7日 下午2:42:39
 * 
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Organization;
import cn.hpclub.server.model.Themes;
import cn.hpclub.server.model.Website;
import cn.hpclub.server.util.CollectionOperator;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.QueryHelper;
import cn.hpclub.server.util.ResultCode;

/**
 * Class description goes here
 *
 * @author
 */
public class WebsiteService{

    private static final Logger  logger  = LoggerFactory.getLogger(WebsiteService.class);
    public static WebsiteService service = new WebsiteService();

    /**
     * 搜索条件封装成map
     * 
     * @return
     */
    public Page<Record> list(int num, int size, ConcurrentHashMap<String, String> map){

        String class_name = (map != null && map.containsKey(Website.WEBSITE_NAME)) ? map.get(Website.WEBSITE_NAME) : "";

        return Website.dao.list(num, size, class_name);
    }

    public Page<Record> auth(int number, int size, int weisiteid, int org_id){
        Object[] p = { weisiteid };
        String SQL_WEBSITE_SELECT = "SELECT distinct " + Constant.Table.ORGANIZATION_CLASS + "." + Website.ID + " as "
                + Website.CLASS_ID + "," + Constant.Table.THEMES + "." + Website.ID + " as " + Website.MODULEID + ","
                + Constant.Table.THEMES + "." + Website.THEMES_NAME + "," + "(select Count(*) from "
                + Constant.Table.ORGANIZATION_CLASS_MAP + " as org where org." + Website.MODULEID + "="
                + Constant.Table.THEMES + "." + Website.ID + " and org." + Website.CLASS_ID + "=" + weisiteid + " and "
                + Website.ORG_ID + "=" + org_id + ") as " + Website.ENABLED;
        // String SQL_WEBSITE_FROM="from "+TABLE_WEBSITE+","+TABLE_THEMES+"
        // where
        // "+TABLE_WEBSITE+"."+COLUMN_WEBSITE_CLASSID+"="+this.getParaToInt(COLUMN_WEBSITE_CLASSID)+"
        // and "+TABLE_THEMES+"."+COLUMN_THEMES_ENABLED+"=1";
        // 增加“政企专区”后，屏蔽该主题参与配置。该主题无需配置，根据客户经理权限进行展示。
        String SQL_WEBSITE_FROM = "from " + Constant.Table.ORGANIZATION_CLASS + "," + Constant.Table.THEMES + " where "
                + Constant.Table.ORGANIZATION_CLASS + "." + Website.ID + "=?" + " and " + Constant.Table.THEMES + "."
                + Website.ENABLED + "='1'" + " and " + Constant.Table.THEMES + "." + Themes.TYPE + "!='5'";

        // System.out.println("SQL_WEBSITE_SELECT:" + SQL_WEBSITE_SELECT);

        // System.out.println("SQL_WEBSITE_FROM:" + SQL_WEBSITE_FROM);

        return Db.paginate(number, size, SQL_WEBSITE_SELECT, SQL_WEBSITE_FROM, p);

    }

    public Page<Record> getOrg(){
        return Db.paginate(1, 100, "select " + Organization.ID + "," + Organization.DISPLAYNAME,
                           "from " + Constant.Table.ORGANIZATION + " where " + Organization.ID + " in "
                                   + InterfaceUtil.getChlidOrgByLevelSql(InterfaceUtil.getOrgId(), 1));

    }

    public void updateWebsites(int moduleId, int pay, int city_org_id, String[] ids){
        // 先这样暴力执法，有时间优化为已经选了的就不要动了

        // 1.先删除原来的关系
        deleteOldWebsites(moduleId, pay, city_org_id, ids);
        // 2.新增现在的
        addNewWebsites(moduleId, pay, city_org_id, ids);
    }

    /**
     * @Title: addNewWebsites
     * @Description:TODO
     * @param moduleId
     * @param pay
     * @param city_org_id
     * @param ids
     *            void
     */
    private void addNewWebsites(int moduleId, int pay, int city_org_id, String[] ids){
        Date date = new Date();
        for(int i = 0; i < ids.length; i++){
            try{
                Db.update("insert into pay_config (module_id,pay_plat,city_org_id,website_id,created_time) values (?,?,?,?,?) ",
                          new Object[] { moduleId, pay, city_org_id, ids[i], date });
            }
            catch(Exception ex){
                ex.printStackTrace();
                continue;
            }
        }
        // StringBuilder sb = new StringBuilder();
        // Date date = new Date();
        // for(int i = 0; i < ids.length; i++){
        // if(i == ids.length - 1){
        // sb.append("(").append(moduleId).append(",").append(pay).append(",").append(city_org_id).append(",")
        // .append(ids[i]).append(",").append(date).append(");");
        // } else{
        // sb.append("(").append(moduleId).append(",").append(pay).append(",").append(city_org_id).append(",")
        // .append(ids[i]).append(",").append(date).append("),");
        // }
        // }
        // // (1,1,54470,172),(1,1,54470,173),(1,1,54470,174);
        // Db.update("insert into pay_config
        // (module_id,pay_plat,city_org_id,website_id,created_time) values "
        // + sb.toString());
        //
        // // betterUpdate(moduleId, pay, org_id, ids);
    }

    /**
     * @Title: deleteOldWebsites
     * @Description:TODO
     * @param moduleId
     * @param pay
     * @param city_org_id
     * @param ids
     *            void
     */
    private void deleteOldWebsites(int moduleId, int pay, int city_org_id, String[] ids){
        for(int i = 0; i < ids.length; i++){
            try{
                Db.update("delete from pay_config where module_id=? and pay_plat=? and city_org_id=? and website_id=?",
                          moduleId, pay, city_org_id, ids[i]);
            }
            catch(Exception ex){
                ex.printStackTrace();
                continue;
            }
        }

    }

    /**
     * @param moduleId
     * @param pay
     * @param city_org_id
     * @param ids
     */
    public void betterUpdate(int moduleId, int pay, int city_org_id, String[] ids){
        // 已经有的就不要动了，减少删除新增的操作

        // 三个数据确定以前的哪些website
        List<Record> list = Db.find(
                                    "select website_id from pay_config where module_id=? and pay_plat=? and city_org_id=?",
                                    moduleId, pay, city_org_id);

        List<String> hasIds = new ArrayList<String>();
        for(Record record : list){
            Integer website_id = record.getInt("website_id");
            hasIds.add(website_id + "");
        }
        List<String> new_ids = Arrays.asList(ids);

        CollectionOperator<String> co = new CollectionOperator<>(new_ids, hasIds);
        Collection<String> intersect = co.diff();// 差集，需要新增的
        /*
         * StringBuffer sb = new StringBuffer(); Iterator<String> iterator =
         * intersect.iterator(); int i = 0; while(iterator.hasNext()){ if(i ==
         * intersect.size() - 1){ sb.append(iterator.next()); } else{
         * sb.append(iterator.next()+","); } }
         */
    }

    /**
     * @Title: getPayConfigSqlExceptSelect
     * @Description:TODO
     * @param moduleId
     * @param payPlat
     * @param orgId
     * @param searchInfo
     * @return String
     */
    public String getPayConfigSqlExceptSelect(int moduleId, int payPlat, int orgId,
            ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = "FROM pay_config pc LEFT JOIN organization_class oc ON oc.id = pc.website_id WHERE pc.module_id = "
                + moduleId + " AND pc.pay_plat = " + payPlat + " AND pc.city_org_id = " + orgId;

        for(Entry<String, String> item : searchInfo.entrySet()){
            if(item.getKey() == "keywordWebsite"){
                sqlExceptSelect += " AND oc.class_name LIKE '%" + item.getValue() + "%' ";
            }
        }
        sqlExceptSelect += " ORDER BY pc.created_time DESC";
        return sqlExceptSelect;
    }

    /**
     * 
     * @Title: queryWebsite
     * @Description:TODO
     * @param pageNumber
     * @param pageSize
     * @param keyword
     * @param queryType
     * @param payId
     * @param moduleId
     * @param cityOrgId
     * @return Page<Record>
     */
    public Page<Record> queryWebsite(int pageNumber, int pageSize, String keyword, String queryType, int moduleId,
            int payId, int cityOrgId){
        return Website.dao.queryWebsite(pageNumber, pageSize, keyword, queryType, moduleId, payId, cityOrgId);
    }

    /**
     * @Title: deletePayWebsite
     * @Description:TODO
     * @param ids
     * @return ResultCode
     */
    public ResultCode deletePayWebsite(String[] ids){
        return deleteRecords("pay_config", ids);
    }

    /**
     * @Title: deleteRecords
     * @Description:批量删除数据
     * @param tableName
     * @param ids
     * @return ResultCode
     */
    private ResultCode deleteRecords(String tableName, String[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("delete from " + tableName + " where id in(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return ResultCode.PARAM_ERROR;
        }
        boolean result = Themes.dao.update(sb.toString(), ids);
        if(result){
            return ResultCode.SUCCESS;
        } else{
            return ResultCode.FAILED;
        }
    }

    /**
     * @Title: getPays
     * @Description:TODO
     * @param moduleId
     * @return List<Record>
     */
    public List<Record> getPays(int moduleId){

        return Website.dao.getPays(moduleId);
    }

    /**
     * @Title: getPayments
     * @Description:TODO
     * @param moduleId
     * @return List<Record>
     */
    public List<Record> getPayments(int moduleId){
        return Website.dao.getPayments(moduleId);
    }
    
    /**
     * 根据parentId获取渠道，渠道大类顶级（0）---渠道簇---渠道类型，如果需要返回所有，那么pageSize设为足够大
     * class_name是为了搜索，不需要的话就为null或者""
     * @return
     */
    public Page<Website> getWebsitesByParentId(Integer parentId,String class_name,Integer pageNumber,Integer pageSize){
        String select = "select oc.*,occ.class_name as parentName";
        String from = "from "+Constant.Table.ORGANIZATION_CLASS+" oc left join "+Constant.Table.ORGANIZATION_CLASS+" occ on occ.id=oc.parentId where oc.parentId=?";
        if(StrKit.notBlank(class_name)){
            from+=" and oc.class_name like ?";
            return Website.dao.paginate(pageNumber, pageSize, select,from ,parentId,"%"+class_name+"%");
        }
        return Website.dao.paginate(pageNumber, pageSize, select,from ,parentId);
    }
    /**
     * 根据层级获取渠道，渠道大类顶级（1）---渠道簇（2）---渠道类型（3）如果需要返回所有，那么pageSize设为足够大
     * @return
     */
    public Page<Website> getWebsitesByLevel(Integer level,Integer pageNumber,Integer pageSize){
        return Website.dao.paginate(pageNumber, pageSize, "select *", "from "+Constant.Table.ORGANIZATION_CLASS+" where level=?",level);
    }

    public Website findById(Integer id){
        //return Website.dao.findById(id);
        return Website.dao.findFirst("select * from "+Constant.Table.ORGANIZATION_CLASS+" where id=?", id);
    }
    

    public int getCityOrgIdByCurrUser(){
        int orgId = InterfaceUtil.getOrgId();
        String cityOrgIdSql = "select CityCode from organization where id=?";
        Record cityOrgRecord = Db.findFirst(cityOrgIdSql,orgId);
        int cityOrgId = cityOrgRecord!=null?cityOrgRecord.getInt(Organization.CITYCODE):0;
        return cityOrgId;
    }

    public Page<Record> getCityPagerForRegular(int pageNumber, int pageSize, int module_id, int pay_plat,
            ConcurrentHashMap<String, String> map){

        QueryHelper helper = new QueryHelper("SELECT pac.id,org.NumCode,org.DisplayName",
                " pay_auth_config pac  LEFT JOIN  "
                        + "(select * from organization where id=CityCode) org ON pac.config_type_id=org.id ");
        helper.addCondition("pac.module_id=? and pac.pay_plat=? and pac.config_type=1 ",
        		module_id, pay_plat);
        helper.addCondition(map.containsKey("keywordCity"), " (org.NumCode LIKE ? OR org.DisplayName LIKE ?)",
                            "%" + map.get("keywordCity") + "%", "%" + map.get("keywordCity") + "%");

        helper.addCondition(map.containsKey("orgId") && !"0".equalsIgnoreCase(map.get("orgId")), " pac.config_type_id=?",map.get("orgId"));


        helper.addOrderProperty("  CONVERT( org.DisplayName USING gbk )  ", true);

        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getStorePagerForRegular(int pageNumber, int pageSize, int module_id,
            int pay_plat, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper("SELECT pac.id,org.NumCode,org.DisplayName",
                " pay_auth_config pac  LEFT JOIN  " + " organization org ON pac.config_type_id=org.id  ");
        helper.addCondition("pac.module_id=? and pac.pay_plat=? and pac.config_type=2 ",
                            module_id, pay_plat);
        helper.addCondition(map.containsKey("keywordOrg"), " (org.NumCode LIKE ? OR org.DisplayName LIKE ?)",
                            "%" + map.get("keywordOrg") + "%", "%" + map.get("keywordOrg") + "%");
        helper.addCondition(map.containsKey("orgId") && !"0".equalsIgnoreCase(map.get("orgId")), " org.CityCode = ?",
                map.get("orgId"));

        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }

    public Page<Record> getMemberPagerForRegular(int pageNumber, int pageSize, int module_id,
            int pay_plat, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(
                " SELECT member.user_name,member.emp_code,member.mobile,member.name,pac.id",
                " pay_auth_config pac  LEFT JOIN  " + " member_org member ON pac.config_type_id=member.id  " +
                        " LEFT JOIN organization o ON member.org_id=o.id ");
        helper.addCondition("pac.module_id=? and pac.pay_plat=? and pac.config_type=3 ",
                            module_id, pay_plat);
        helper.addCondition(map.containsKey("keywordMember"),
                            " (member.user_name LIKE ? OR member.emp_code LIKE ? OR member.name LIKE ?)",
                            "%" + map.get("keywordMember") + "%", "%" + map.get("keywordMember") + "%",
                            "%" + map.get("keywordMember") + "%");
        helper.addCondition(map.containsKey("orgId") && !"0".equalsIgnoreCase(map.get("orgId")), " o.CityCode = ?",
                map.get("orgId"));
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }
    
    public Page<Record> getChannelClassPagerForRegular(int pageNumber, int pageSize, int module_id,
            int pay_plat, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,pac.id",
                " pay_auth_config pac  LEFT JOIN  " + " organization_class oc ON pac.config_type_id=oc.id  LEFT JOIN organization o ON pac.created_org_id=o.id ");
        helper.addCondition("pac.module_id=? and pac.pay_plat=? and pac.config_type=4 ",
                            module_id, pay_plat);
        helper.addCondition(map.containsKey("keywordChannelClass"), " (oc.WebsiteId LIKE ? OR oc.class_name LIKE ? )",
                            "%" + map.get("keywordChannelClass") + "%", "%" + map.get("keywordChannelClass") + "%");



        helper.addCondition(map.containsKey("orgId")  && !"0".equalsIgnoreCase(map.get("orgId")), " o.CityCode=?",
                map.get("orgId"));
       
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }
    
    public Page<Record> getChannelClusterPagerForRegular(int pageNumber, int pageSize, int module_id,
            int pay_plat, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,pac.id",
                " pay_auth_config pac  LEFT JOIN  " + " organization_class oc ON pac.config_type_id=oc.id  " +
                        " LEFT JOIN organization o ON pac.created_org_id=o.id  ");
        helper.addCondition("pac.module_id=? and pac.pay_plat=? and pac.config_type=5 ",
                            module_id, pay_plat);
        helper.addCondition(map.containsKey("keywordChannelCluster"), " (oc.WebsiteId LIKE ? OR oc.class_name LIKE ? )",
                            "%" + map.get("keywordChannelCluster") + "%", "%" + map.get("keywordChannelCluster") + "%");

        helper.addCondition(map.containsKey("orgId")  && !"0".equalsIgnoreCase(map.get("orgId")), " o.CityCode=?",
                map.get("orgId"));

        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }
    
    public Page<Record> getChannelTypePagerForRegular(int pageNumber, int pageSize, int module_id,
            int pay_plat, ConcurrentHashMap<String, String> map){
        QueryHelper helper = new QueryHelper(" SELECT oc.WebsiteId,oc.class_name,pac.id",
                " pay_auth_config pac  LEFT JOIN  " + " organization_class oc ON pac.config_type_id=oc.id  " +
                        " LEFT JOIN organization o ON pac.created_org_id=o.id   ");
        helper.addCondition("pac.module_id=? and pac.pay_plat=? and pac.config_type=6 ",
                            module_id, pay_plat);
        helper.addCondition(map.containsKey("keywordChannelType"), " (oc.WebsiteId LIKE ? OR oc.class_name LIKE ? )",
                            "%" + map.get("keywordChannelType") + "%", "%" + map.get("keywordChannelType") + "%");

        helper.addCondition(map.containsKey("orgId")  && !"0".equalsIgnoreCase(map.get("orgId")), " o.CityCode=?",
                map.get("orgId"));

        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }
    
    public Page<Record> getCity(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map, String operation,
            int module_id, int pay_plat, String flowId){
        QueryHelper helper = new QueryHelper("SELECT *", Constant.Table.ORGANIZATION, "org");
        helper.addCondition("org.CityCode=org.id ");
        helper.addCondition("org.id in " + InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), 1, true));

        //if("edit".equalsIgnoreCase(operation)){
            helper.addCondition("org.id not in(select config_type_id from pay_auth_config WHERE config_type=1 AND module_id=? and pay_plat=? ) ",
            		module_id, pay_plat);
//        } else if("add".equalsIgnoreCase(operation)){
//            helper.addCondition("org.id not in(SELECT config_type_id from pay_auth_config con WHERE config_type=1 AND flow_id=?)",
//                                flowId);
//        }
        String exact = map.get("queryType");
        helper.addCondition(map.containsKey("keyword") && !"exact".equals(exact), "(org.DisplayName LIKE ?)",
                            "%" + map.get("keyword") + "%");
        helper.addCondition(map.containsKey("keyword") && "exact".equals(exact), "(org.DisplayName = ?)",
                            map.get("keyword"));
       
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }
    
    public Page<Record> getStore(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map,String operation,
            int module_id, int pay_plat, String flowId){
        QueryHelper helper = new QueryHelper("SELECT org.*", Constant.Table.ORGANIZATION, "org");
        /* helper.addCondition("org.parentid=org.AreaCode"); */
        // helper.addCondition("org.parentid>0");
        helper.addCondition(" AreaCode = parentid");
        helper.addCondition(" AreaCode != 0");
        helper.addCondition("org.id in "
                + InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), Constant.MAX_ORG_LEVEL, true));
        //if("edit".equalsIgnoreCase(operation)){
            helper.addCondition("org.id not in(select config_type_id from pay_auth_config WHERE config_type=2 AND module_id=? and pay_plat=? ) ",
            		module_id, pay_plat);
//        } else if("add".equalsIgnoreCase(operation)){
//            helper.addCondition("org.id not in(SELECT config_type_id from pay_auth_config con WHERE config_type=2 AND flow_id=?)",
//                                flowId);
//        }
        helper.addCondition("org.is_deleted=0");
        String exact = map.get("queryType");
        helper.addCondition(map.containsKey("keyword") && !"exact".equals(exact), "(org.DisplayName LIKE ?)",
                            "%" + map.get("keyword") + "%");
        helper.addCondition(map.containsKey("keyword") && "exact".equals(exact), "(org.DisplayName = ?)",
                            map.get("keyword"));
     
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }
    
    public Page<Record> getMember(int pageNumber, int pageSize, ConcurrentHashMap<String, String> map,String operation,
            int module_id, int pay_plat, String flowId){
        QueryHelper helper = new QueryHelper("select mo.id,mo.name,mo.emp_code,mo.mobile", Constant.Table.MEMBER_ORG,
                "mo");
        String orgFilter = InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), Constant.MAX_ORG_LEVEL, true);
        helper.addCondition("mo.org_id IN" + orgFilter);
        //if("edit".equalsIgnoreCase(operation)){
            helper.addCondition("mo.id not in(select config_type_id from pay_auth_config WHERE config_type=3 AND module_id=? and pay_plat=? ) ",
            		module_id, pay_plat);
//        } else if("add".equalsIgnoreCase(operation)){
//            helper.addCondition("mo.id not in(SELECT config_type_id from pay_auth_config con WHERE config_type=3 AND flow_id=?)",
//                                flowId);
//        }
        helper.addCondition("mo.enabled=1");
        helper.addCondition("mo.is_deleted=0");
        //helper.addCondition("mo.member_type!=3");//此处不应该限制泛店员
        helper.addCondition(map.containsKey("keyword"), "(mo.name like ? or mo.user_name =? or mo.mobile=?)",
                            "%" + map.get("keyword") + "%", map.get("keyword"), map.get("keyword"));

        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }
    
    public Page<Record> getChannel(int type, int pageNumber, int pageSize, ConcurrentHashMap<String, String> map,String operation,
            int module_id, int pay_plat, String flowId){
        QueryHelper helper = new QueryHelper("select *", Constant.Table.ORGANIZATION_CLASS, "oc");
        helper.addCondition("oc.level=?", type - 3);// type-3正好是其层级
        //if("edit".equalsIgnoreCase(operation)){
            helper.addCondition("oc.id not in(select config_type_id from pay_auth_config WHERE config_type=? AND module_id=? and pay_plat=? ) ",
            		type,module_id, pay_plat);
//        } else if("add".equalsIgnoreCase(operation)){
//            helper.addCondition("oc.id not in(SELECT config_type_id from pay_auth_config con WHERE config_type=? AND flow_id=?)",
//            		type,flowId);
//        }
        String exact = map.get("queryType");
        helper.addCondition(map.containsKey("keyword") && !"exact".equals(exact),
                            "(oc.class_name like ? or oc.WebsiteId LIKE ?)", "%" + map.get("keyword") + "%",
                            "%" + map.get("keyword") + "%");
        helper.addCondition(map.containsKey("keyword") && "exact".equals(exact), "(oc.class_name= ? or oc.WebsiteId=?)",
                            map.get("keyword"), map.get("keyword"));
     
        Page<Record> page = Db.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return page;
    }
    
    public boolean saveByType(int type, Integer[] ids, int module_id, int pay_plat){
        StringBuffer sb = new StringBuffer();
        Date now = new Date();
        sb.append("INSERT INTO pay_auth_config (config_type,config_type_id,module_id,pay_plat,created_time,created_org_id) VALUES(?,?,?,?,?,?)");
        int orgId = InterfaceUtil.getOrgId();
        for(int id : ids){
            // 查询数据是否已存在，存在就直接跳过
            String selectExistData = "select * from pay_auth_config WHERE config_type=? AND config_type_id=?"
                    + " AND module_id=? AND pay_plat=? ";
     
            Record record = Db.findFirst(selectExistData, type, id, module_id, pay_plat);
            if(record != null && record.getInt("id") > 0){
                continue;
            }
            Db.update(sb.toString(), type, id, module_id, pay_plat, now,orgId);
        }
        return true;
    }
    
    /**
     * 删除正式表数据
     * 
     * @param
     * @param ids
     * @return
     */
    public boolean deleteByType(Integer[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("DELETE FROM pay_auth_config WHERE id in(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return false;
        }
        return Db.update(sb.toString(), (Object[])ids) > 0;
    }



}
